// 目前没有针对uni的Fly版本，使用wx版本没有问题
import router from '@/router'
import store from '@/store'
import Fly from 'flyio/dist/npm/fly'
import {LoadingBar, Message} from 'iview'

const request = new Fly();

request.interceptors.request.use((request) => {
  LoadingBar.start();
  console.log(request);
  
  const token = store.getters['token/getToken'];
  // const token= store.state.token.value;
  // if(!helper.isEmpty(token)) {
  if(token) {
    //给所有请求添加自定义header
    request.headers["Authorization"] = token;
  }
  request.baseURL = 'http://127.0.0.1:8360/admin';
  
  //request.params = {
  //  ...request.params,
  //  _t: Date.parse(new Date()) / 1000
  //};
  
  // 防止缓存
  if(request.method === 'POST' && request.headers['Content-Type'] !== 'multipart/form-data') {
    request.body = {
      ...request.body,
      _t: Date.parse(new Date()) / 1000
    }
  } else if(request.method === 'GET') {
    request.params = {
      _t: Date.parse(new Date()) / 1000,
      ...request.params
    }
  }
  
  return request
})

request.interceptors.response.use(
  function (response) {  //不要使用箭头函数，否则调用this.lock()时，this指向不对 {
    
    const data = response.data;
    
    if(!data || typeof data !== 'object') {
      LoadingBar.error();
      Message.error('服务器响应格式错误')
    } else {
      let errmsg = '';
      const errno = data.errno;
      switch (errno) {
        case 1001:
          // 数据检验未通过
          for (let i in data.data) {
            errmsg += data.data[i] + ';'
          }
          break;
        default:
          errmsg = data.errmsg;
          break
      }
      
      if(errmsg !== '' && errno !== 0) {
        Message.error(errmsg)
      }
      if(errmsg !== '' && errno === 0) {
        Message.success(errmsg)
      }
    }
    LoadingBar.finish();
    
    return response.data;
    
  }, function (err) {
    console.log("error-interceptor:" + JSON.stringify(err))
    
    let errmsg = err.message;
    
    
    switch (err.status) {
      case 0:
        errmsg = "网络连接错误";
        break;
      case 401:
        errmsg = '请登录后操作';
        store.dispatch('logout');
        router.replace('/login');
        break
    }
    LoadingBar.error();
    Message.error(errmsg);
  }
)

export default request
